package com.example.app.ui.Messages;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app.R;

import java.util.List;

public class MessagesAdapter extends BaseAdapter {
    private Context context;
    private List<Message> messages;
    private LayoutInflater inflater;

    public MessagesAdapter(Context context, List<Message> messages) {
        this.context = context;
        this.messages = messages;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return messages.size();
    }

    @Override
    public Message getItem(int position) {
        return messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.messages, parent, false);
            holder = new ViewHolder();
            holder.avatar = convertView.findViewById(R.id.avatar_iv);
            holder.sender = convertView.findViewById(R.id.sender_tv);
            holder.lastMessage = convertView.findViewById(R.id.last_message_tv);
            holder.time = convertView.findViewById(R.id.time_tv);
            holder.unread = convertView.findViewById(R.id.unread_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Message message = getItem(position);
        holder.avatar.setImageResource(message.getAvatarResId());
        holder.sender.setText(message.getSender());
        holder.lastMessage.setText(message.getLastMessage());
        holder.time.setText(message.getTime());

        if (message.getUnreadCount() > 0) {
            holder.unread.setVisibility(View.VISIBLE);
            holder.unread.setText(String.valueOf(message.getUnreadCount()));
        } else {
            holder.unread.setVisibility(View.GONE);
        }

        return convertView;
    }

    static class ViewHolder {
        ImageView avatar;
        TextView sender;
        TextView lastMessage;
        TextView time;
        TextView unread;
    }
}